package physics;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import physics.collision.Collidable;
import physics.collision.CollisionEvent;


/**
 * This class is responsible for applying all global forces to GameObjects, as
 * well as for checking and handling collisions between GameObjects.
 * 
 * @author geo4
 * 
 */
public class PhysicsManager {

    private ArrayList<EuclideanVector> myForces;

    /**
     * Constructs a new PhysicsManager with the global forces specified.
     * 
     * @param forces forces to be applied to GameObjects
     */
    public PhysicsManager (Collection<EuclideanVector> forces) {
        myForces = new ArrayList<EuclideanVector>(forces);
    }

    /**
     * Checks for collisions between a Collection of type Collidable. If two
     * objects have in fact collided, they are both instructed to handle the
     * CollisionEvent once all collisions have been checked.
     * 
     * @param collidableObjects a Collection of items that should be checked to
     *        see if they have collided.
     */
    public void checkAndApplyCollisions (Collection<Collidable> collidableObjects) {
        Map<Collidable, CollisionEvent> collisionMap = new HashMap<Collidable, CollisionEvent>();

        Collidable[] collidables = new Collidable[collidableObjects.size()];
        collidables = collidableObjects.toArray(collidables);
        for (int i = 0; i < collidables.length - 2; i++) {
            for (int j = i + 1; j < collidables.length - 1; j++) {
                CollisionEvent c = collidables[i].checkCollision(collidables[j]);
                collisionMap.put(collidables[i], c);
                collisionMap.put(collidables[j], c.invertCollision());
            }
        }

        for (Collidable c : collisionMap.keySet()) {
            c.handleCollision(collisionMap.get(c));
        }
    }

}
